#!/bin/bash

# 处理命令行参数
if [ $# -eq 1 ]; then
    if ! [[ $1 =~ ^[0-9]+$ ]]; then
        echo "错误：请输入有效的正整数分钟数"
        exit 1
    fi
    total_duration=$(( $1 * 60 ))
else
    total_duration=3600  # 默认60分钟
fi

home_dir="${HOME}"
# 创建带时间戳的日志目录
timestamp=$(date +%Y%m%d-%H%M%S)
log_path="$home_dir/logs/$timestamp"
mkdir -p "$log_path"

# 启动Topic测试并保存进程PID
echo "Starting Topic Test..."
current_dir=$(pwd)
#export RMW_IMPLEMENTATION=rmw_fastrtps_cpp
#export FASTRTPS_DEFAULT_PROFILES_FILE=${current_dir}/dds_config.xml

python3 publisher.py > /dev/null 2>&1 &
PUB_PID=$!
python3 -u subscriber.py > $log_path/topic_test.log 2>&1 &
SUB_PID=$!
 
# 启动Latency测试并保存进程PID
echo "Starting Latency Test..."
python3 latency_pub.py > /dev/null 2>&1 &
LPUB_PID=$!
python3 -u latency_sub.py > $log_path/latency_test.log 2>&1 &
LSUB_PID=$!
 
# 设置超时定时器
echo "Tests will run for $TEST_DURATION minutes..."

# 初始化资源监控文件
touch "$log_path/resource_monitor.log"

# 设置超时定时器
echo "测试将持续运行 $((total_duration/60)) 分钟..."

log_file="$log_path/resource_monitor.log"

printf "%-12s | %-12s | %-12s | %-12s\n" "TIME" "PID" "CPU(%)" "MEM(%)" > "$log_file"
printf "%-12s | %-12s | %-12s | %-12s\n" "-----------" "-----------" "----------" "----------" >> "$log_file"

elapsed_time=0

# 循环执行测试
while [ $elapsed_time -lt $total_duration ]; do
    sleep 1
    elapsed_time=$((elapsed_time + 1))
    remaining_time=$((total_duration - elapsed_time))
    
    # 记录资源使用情况
    {
        # 初始化PID列表和结果数组
        pids=($PUB_PID $SUB_PID $LPUB_PID $LSUB_PID)
        cpu_arr=()
        mem_arr=()
 
        # 收集所有进程的数据
        for pid in "${pids[@]}"; do
            if ps -p $pid > /dev/null; then
                cpu_usage=$(ps -p $pid -o %cpu | tail -1 | awk '{print $1}')
                mem_usage=$(ps -p $pid -o %mem | tail -1 | awk '{print $1}')
                cpu_arr+=("$cpu_usage")
                mem_arr+=("$mem_usage")
            else
                # 进程已退出，填充空值
                cpu_arr+=("N/A")
                mem_arr+=("N/A")
            fi
        done
 
        # 构建输出格式
        timestamp=$(date +%Y-%m-%d\ %H:%M:%S)
        pid_str=$(IFS=' | '; echo "${pids[*]}")
        cpu_str=$(IFS=' | '; echo "${cpu_arr[*]}")
        mem_str=$(IFS=' | '; echo "${mem_arr[*]}")
 
        # 写入日志文件
        printf "%-12s | %-12s | %-12s | %-12s\n" "$timestamp" "$pid_str" "$cpu_str" "$mem_str" >> "$log_file"
    }

    # 输出进度
    if [ $((elapsed_time % 60)) -eq 0 ]; then
      echo "已测试时间: $((elapsed_time / 60)) 分钟，剩余时间: $((remaining_time / 60)) 分钟"
    fi

done

echo "测试完成！"

# 关闭所有测试进程
echo "Stopping all tests..."
kill $PUB_PID $SUB_PID $LPUB_PID $LSUB_PID 2>/dev/null
wait $PUB_PID $SUB_PID $LPUB_PID $LSUB_PID 2>/dev/null
 
echo "All tests completed and processes terminated."
echo "所有测试已完成且进程已终止。"
echo "日志文件保存在 logs/$timestamp 目录中"